<template>
  <div>
    <el-row :gutter="20">
      <el-col
        :span="18"
        :xs="24"
      >
        <el-button
          :disabled="step!=2&&step!=4"
          type="danger"
          style="margin-left:10px;margin-top:10px;margin-bottom:-10px;width: 140px"
          @click="cancelOrder"
        >{{$t('sale_cash_cash_195')}}</el-button>
        <template>
          <div
            class="marquee-container"
          >
            <marquee
              behavior=""
              direction="111"
              class="marquee-text"
            >
              {{ scrollingText }}{{ scrollingText }}
            </marquee>
          </div>
        </template>
        <el-descriptions
          border
          style="margin-top:20px; margin-left:10px;"
          :content-style="CS"
          :label-style="LS "
        >
          <el-descriptions-item
            :label="$t('sale_cash_cash_196')"
          >
            {{ orderInfo.saleNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_cash_cash_197')">
            {{ orderInfo.total }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_cash_cash_198')">
            {{ orderInfo.note }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_cash_cash_199')">
            {{ orderInfo.quantity }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_cash_cash_200')">
            <el-tag size="small">
              {{ orderInfo.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <el-button
              :disabled="step!=2"
              @click="openBeizhu"
            >{{$t('sale_cash_cash_201')}}</el-button>
          </el-descriptions-item>
        </el-descriptions>
        <br>
        <el-card
          class="box-card"
          style="margin-left: 10px"
        >
          <div
            slot="header"
            class="clearfix"
          >
            <span>{{$t('sale_cash_cash_202')}}</span>
          </div>
          <el-table
            :data="saleItemList"
            :row-class-name="rowSaleItemIndex"
            style="width: 100%"
          >
            <el-table-column
              :label="$t('sale_cash_cash_203')"
              align="center"
              prop="index"
              width="80"
            />
            <el-table-column
              :label="$t('sale_cash_cash_204')"
              align="center"
              prop="productSn"
              width="95"
            />
            <el-table-column
              :label="$t('sale_cash_cash_205')"
              align="center"
              prop="productName"
              width="80"
              show-overflow-tooltip
            />
            <el-table-column
              :label="$t('sale_cash_cash_206')"
              align="center"
            >
              <template slot-scope="scope">
                <img
                  v-if="scope.row.imageUrl != null"
                  :src="scope.row.imageUrl"
                  alt="Item Image"
                  style="width: 120px; height: auto"
                >
                <span v-else>{{$t('sale_cash_cash_207')}}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('sale_cash_cash_208')"
              align="center"
              prop="price"
              width="60"
            />
            <el-table-column
              :label="$t('sale_cash_cash_209')"
              align="center"
              prop="speId"
              width="110"
            >
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.speId"
                  :placeholder="$t('sale_cash_cash_210')"
                  :disabled="step !== 2"
                  @visible-change="handleVisibleChange(scope.row)"
                  @change="handleUpdateSpec(scope.row)"
                >
                  <el-option
                    v-for="item in scope.row.speList"
                    :key="item.id"
                    :label="item.color + ',' + item.size"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('sale_cash_cash_211')"
              align="center"
              prop="quantity"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  :disabled="step !== 2"
                  :min="1"
                  size="small"
                  @change="handleChangeQuantity(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('sale_cash_cash_212')"
              align="center"
              class-name="small-padding fixed-width"
              width="80"
            >
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  :disabled="step !== 2"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >{{$t('sale_cash_cash_213')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col
        :span="6"
        :xs="24"
      >
        <el-button
          type="success"
          size="mini"
          :disabled="step !== 1&&step!==4"
          style="margin-top: 20px; font-size: 13px; height: 35px"
          @click="makeNewSale"
        >{{$t('sale_cash_cash_214')}}</el-button>
        <el-button
          type="info"
          size="mini"
          :disabled="step !== 2 || saleItemList.length == 0"
          style="margin-top: 20px; font-size: 13px; height: 35px"

          @click="pendingOrders"
        >{{$t('sale_cash_cash_215')}}</el-button>
        <el-button
          class="unfinish-Button"
          size="mini"
          :disabled="step!==1"
          @click="queryUnfinishedSale('queryAll')"
        >{{$t('sale_cash_cash_216')}}</el-button>
        <el-card
          class="box-card"
          style="margin-right: 10px; margin-top: 10px"
        >
          <div
            slot="header"
            class="clearfix"
          >
            <span>{{$t('sale_cash_cash_217')}}</span>
          </div>
          <el-form
            ref="enterItemForm"
            :model="enterItemForm"
            :rules="enterItemRules"
            :hide-required-asterisk="true"
            size="small"
            label-width="68px"
          >
            <el-form-item
              :label="$t('sale_cash_cash_218')"
              prop="productSn"
            >
              <el-input
                v-model="enterItemForm.productSn"
                :placeholder="$t('sale_cash_cash_219')"
                :disabled="step !== 2"
                clearable
                @blur="handleBlur"
              />
            </el-form-item>
            <el-form-item
              :label="$t('sale_cash_cash_220')"
              prop="speId"
            >
              <el-select
                v-model="enterItemForm.speId"
                :placeholder="$t('sale_cash_cash_221')"
                :disabled="step !== 2"
                @change="handleSpecChange"
              >
                <el-option
                  v-for="item in specificationOptions"
                  :key="item.id"
                  :label="item.color +','+ item.size"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('sale_cash_cash_222')"
              prop="quantity"
            >
              <template>
                <el-input-number
                  v-model="enterItemForm.quantity"
                  :disabled="step !== 2"
                  style="width: 155px"
                  :min="1"
                  :max="999"
                />
              </template>
            </el-form-item>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-button
                  size="mini"
                  :disabled="step !== 2"
                  class="enterItemButton"
                  @click="enterItem"
                >{{$t('sale_cash_cash_223')}}</el-button>
              </el-col>
              <el-col :span="8">
                <el-button
                  size="mini"
                  :disabled="step !== 2"
                  class="resetButton"
                  @click="clearEnterItemForm"
                >{{$t('sale_cash_cash_224')}}</el-button>
              </el-col>
              <el-col :span="8">
                <el-button
                  size="mini"
                  :disabled="step !== 2 || saleItemList.length == 0"
                  class="endSaleButton"
                  @click="endSale"
                >{{$t('sale_cash_cash_225')}}</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <el-card
          class="box-card"
          style="margin-right: 10px; margin-top: 20px"
        >
          <div
            slot="header"
            class="clearfix"
          >
            <span>{{$t('sale_cash_cash_226')}}</span>
          </div>
          <el-form
            ref="makePaymentForm"
            :model="makePaymentForm"
            :rules="payRules"
            :hide-required-asterisk="true"
            size="small"
            label-width="68px"
          >
            <el-form-item>
              <el-button
                type="danger"
                size="small"
                :disabled="step !== 4"
                style="width: 155px; margin-left: -25px"
                @click="openMakePayment"
              >{{$t('sale_cash_cash_227')}}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <!-- 查看未完成订单弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_cash_cash_216')"
      :visible.sync="unfinishedOpen"
      width="80%"
      append-to-body
    >
      <el-form
        ref="UnfinishedSaleForm"
        :inline="true"
        :model="queryUnfinishedSaleParams"
        class="demo-form-inline"
      >
        <el-form-item
          :label="$t('sale_cash_cash_228')"
          prop="status"
        >
          <el-select
            v-model="queryUnfinishedSaleParams.status"
            :placeholder="$t('sale_cash_cash_221')"
          >
            <el-option
              :label="$t('sale_cash_cash_229')"
              value="1"
            />
            <el-option
              :label="$t('sale_cash_cash_230')"
              value="2"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('sale_cash_cash_196')">
          <el-input
            v-model="queryUnfinishedSaleParams.saleNo"
            :placeholder="$t('sale_cash_cash_231')"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            class="unfinishedDialogResetButton"
            @click="resetQueryUnfinishedSale"
          >{{$t('sale_cash_cash_224')}}</el-button>
          <el-button
            class="unfinishedDialogQueryButton"
            @click="queryUnfinishedSale('query')"
          >{{$t('sale_cash_cash_232')}}</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="unfinishedData"
        style="width: 100%"
        height="350"
      >
        <el-table-column
          show-overflow-tooltip
          prop="saleNo"
          align="center"
          :label="$t('sale_cash_cash_196')"
          width="200"
        />
        <el-table-column
          prop="quantity"
          align="center"
          :label="$t('sale_cash_cash_233')"
        />
        <el-table-column
          prop="total"
          :label="$t('sale_cash_cash_234')"
          align="center"
        />
        <el-table-column
          :label="$t('sale_cash_cash_200')"
          align="center"
        >
          <template v-slot:default="scope">
            <span v-if="scope.row.status === 1">{{$t('sale_cash_cash_229')}}</span>
            <span v-else-if="scope.row.status === 2">{{$t('sale_cash_cash_230')}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="note"
          :label="$t('sale_cash_cash_198')"
          align="center"
        >
          <template v-slot:default="scope">
            <span v-if="scope.row.note == null">{{$t('sale_cash_cash_235')}}</span>
            <span v-else>{{ scope.row.note }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTimeString"
          :label="$t('sale_cash_cash_236')"
          align="center"
          width="180"
        />
        <el-table-column :label="$t('sale_cash_cash_212')">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              icon="el-icon-right"
              @click="continueSale(scope.row)"
            >
              {{ scope.row.status === 2 ? $t('sale_cash_cash_237') : $t('sale_cash_cash_238') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 确认支付弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_cash_cash_226')"
      :visible.sync="paymentOpen"
      width="400px"
      append-to-body
    >
      <el-form
        ref="makePaymentForm"
        label-position="left"
        label-width="20%"
        :hide-required-asterisk="true"
        :model="makePaymentForm"
        :rules="payRules"
      >
        <el-form-item
          :label="$t('sale_cash_cash_239')"
          style="margin-bottom: 5px;"
          prop="total"
        >
          <span>{{ makePaymentForm.total }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_240')"
          style="margin-bottom: 5px;"
          prop="discount"
        >
          <span>{{ makePaymentForm.discount }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_241')"
          style="margin-bottom: 5px;"
          prop="preferentialTotal"
        >
          <span>{{ makePaymentForm.preferentialTotal }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_242')"
          style="margin-bottom: 5px;"
          prop="payType"
        >
          <el-select
            v-model="makePaymentForm.payType"
            :placeholder="$t('sale_cash_cash_221')"
            clearable
          >
            <el-option
              v-for="item in payTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_243')"
          style="margin-bottom: 5px;"
          prop="cashTendered"
        >
          <el-input
            v-model="makePaymentForm.cashTendered"
            :disabled="step !== 4 || makePaymentForm.payType === 2"
          />
        </el-form-item>
        <el-form-item
          v-if="makePaymentForm.payType === 1"
          :label="$t('sale_cash_cash_244')"
          style="margin-bottom: 15px;"
        >
          <el-input
            v-model="changeDue"
            disabled
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="paymentOpen = false"
        >{{$t('sale_cash_cash_245')}}</el-button>
        <el-button
          type="danger"
          @click="makePayment"
        >{{$t('sale_cash_cash_246')}}</el-button>
      </span>
    </el-dialog>
    <!-- 订单支付明细弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_cash_cash_247')"
      :visible.sync="paymentDetailOpen"
      width="400px"
      append-to-body
    >
      <el-form
        ref="paymentDetailForm"
        label-position="left"
        label-width="20%"
        :hide-required-asterisk="true"
        :model="paymentDetailForm"
      >
        <el-form-item
          :label="$t('sale_cash_cash_239')"
          style="margin-bottom: 5px;"
          prop="total"
        >
          <span>{{ paymentDetailForm.total }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_240')"
          style="margin-bottom: 5px;"
          prop="differ"
        >
          <span>{{ paymentDetailForm.differ }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_241')"
          style="margin-bottom: 5px;"
          prop="preferentialTotal"
        >
          <span>{{ paymentDetailForm.preferentialTotal }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_248')"
          style="margin-bottom: 5px;"
          prop="promotionDesc"
        >
          <span>{{ paymentDetailForm.promotionDesc }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_242')"
          style="margin-bottom: 5px;"
          prop="payType"
        >
          <span v-if="paymentDetailForm.payType === 1">{{$t('sale_cash_cash_249')}}</span>
          <span v-if="paymentDetailForm.payType === 2">{{$t('sale_cash_cash_250')}}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_251')"
          style="margin-bottom: 5px;"
          prop="payAmount"
        >
          <span>{{ paymentDetailForm.payAmount }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_244')"
          style="margin-bottom: 5px;"
          prop="change"
        >
          <span>{{ paymentDetailForm.change }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_cash_cash_252')"
          style="margin-bottom: 5px;"
          prop="payTime"
        >
          <span>{{ paymentDetailForm.payTime }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 支付宝支付状态，默认不显示 -->
    <el-dialog
      :title="$t('sale_cash_cash_226')"
      :visible.sync="alipayOpen"
      width="400px"
      append-to-body
    >
      <span>{{$t('sale_cash_cash_253')}}</span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="alipayOpen = false"
        >{{$t('sale_cash_cash_245')}}</el-button>
        <el-button
          type="primary"
          @click="queryAliPayment"
        >{{$t('sale_cash_cash_254')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  cancelOrder,
  changeSaleItem,
  deleteItem,
  endSale,
  enterItem,
  getPayDetail,
  getSpecificationList,
  getUnfinishedSale,
  loadSale,
  makeNewSale,
  pendingSale
} from '@/api/cash'
import { aliPay, cashPay, openPay, verifyAliPay } from '@/api/payment'
import { listPromotion } from '@/api/promotion'

export default {
  name: 'Sale',
  // 定义属性
  data() {
    return {
      CS: {
        // 'text-align': 'center',  //文本居中
        'min-width': '150px'   //最小宽度
      },
      LS: {
        'text-align': 'center',  //文本居中
        'min-width': '100px'   //最小宽度
      },
      // 滚动展示优惠政策
      scrollingText: this.$t('sale_cash_cash_255'),
      animationDuration: 15, // 动画持续时间（秒）

      // 当前步骤，用于控制按钮是否可用
      step: 1,
      //找零
      changeDue: '',
      //展示栏数据
      orderInfo: {
        note: ''
      },
      //表格数据
      saleItemList: [],
      //规格
      specificationOptions: [],
      // 订单号
      saleNo: '',
      //修改商品
      updateSaleItem: {
        productSn: '',
        originalSpeId: '',
        finalSpeId: '',
        color: '',
        size: '',
        quantity: null
      },
      //商品输入表单
      enterItemForm: {
        quantity: 1,
        color: '',
        size: ''
      },
      // 下拉框选项数据
      payTypeOptions: [
        {
          value: 1,
          label: this.$t('sale_cash_cash_249')
        },
        {
          value: 2,
          label: this.$t('sale_cash_cash_250')
        }
      ],
      //是否显示未完成订单遮罩层
      unfinishedOpen: false,
      //是否显示支付页面遮罩层
      paymentOpen: false,
      //是否显示支付明细页面遮罩层
      paymentDetailOpen: false,
      // 支付宝支付遮罩层
      alipayOpen: false,
      //挂单时间
      createTime: [],
      // 订单支付表单
      makePaymentForm: {
        cashTendered: '',
        payType: 1,
        total: '',
        discount: '',
        preferentialTotal: ''
      },
      // 订单明细表单
      paymentDetailForm: [],
      // 未完成订单
      unfinishedData: [],
      // 查询未完成订单参数
      queryUnfinishedSaleParams: {
        saleNo: '',
        status: ''
      },
      // 表单校验
      enterItemRules: {
        productSn: [
          { required: true, message: this.$t('sale_cash_cash_256') }
        ],
        speId: [
          { required: true, message: this.$t('sale_cash_cash_257') }
        ],
        quantity: [
          { required: true, message: this.$t('sale_cash_cash_258') }
        ]
      },
      payRules: {
        cashTendered: [
          { required: true, message: this.$t('sale_cash_cash_259'), trigger: 'blur' }
        ]
      }
    }
  },
  // 计算属性
  computed: {},
  watch: {},
  // 生命周期-创建完成
  created() {
    this.$bus.$on('continueSale', (saleNo) => {
      // console.log(this.$t('sale_cash_cash_260'), saleNo)
      this.continueSale({ saleNo })
    })
    this.$bus.$emit('saleReady')
    listPromotion().then((response) => {
      this.scrollingText = response.data.join(', ') + ' ,'
    })
  },
  beforeDestroy() {
    this.$bus.$off('continueSale')
    this.$bus.$off('saleReady')
  },
  // 方法集合
  methods: {
    //步骤1：创建订单
    makeNewSale() {
      this.clear()
      makeNewSale().then((response) => {
        this.orderInfo = response.data
        if (response.data.status == 0) {
          this.orderInfo.status = this.$t('sale_cash_cash_261')
        }
        this.step = 2
      })
    },
    // 步骤2：提交输入商品
    // 商品编码失焦查询规格
    handleBlur() {
      getSpecificationList(this.enterItemForm.productSn).then((response) => {
        this.specificationOptions = response.data
      })
    },
    // 规范化enterItemForm以便传入后端
    handleSpecChange(speId) {
      const selectedSpec = this.specificationOptions.find(
        (item) => item.id === speId
      )
      this.enterItemForm.color = selectedSpec.color
      this.enterItemForm.size = selectedSpec.size
    },
    // 规范化updateSaleItem以便传入后端
    standardizeUpdateSaleParams(row) {
      const selectedSpec = row.speList.find(
        (item) => item.id === row.speId
      )
      this.updateSaleItem.color = selectedSpec.color
      this.updateSaleItem.size = selectedSpec.size
      this.updateSaleItem.productSn = row.productSn,
        this.updateSaleItem.quantity = row.quantity
    },
    handleVisibleChange(row) {
      // 下拉框变得可见时（即用户准备选择），保存旧的 speId
      this.$set(row, 'oldSpeId', row.speId)
    },
    // 修改商品规格
    handleUpdateSpec(row) {
      const oldSpeId = row.oldSpeId // 获取保存的旧 speId
      const newSpeId = row.speId // 获取用户选择的新 speId
      this.updateSaleItem.originalSpeId = Number(oldSpeId)
      this.updateSaleItem.finalSpeId = Number(newSpeId)
      this.standardizeUpdateSaleParams(row)
      changeSaleItem(this.updateSaleItem).then((response) => {
        if (response.data == 1)// 单纯修改
        {
          this.$message.success(this.$t('sale_cash_cash_262'))
        } else if (response.data > 1) {// 有合并
          // 找到修改之后与之相同的另一个row，把那行的quantity加到这行，再删除这行
          const existingItem = this.saleItemList.find(item => item.productSn === row.productSn && item.speId === row.speId)
          existingItem.quantity += row.quantity
          // 把现在选中这行删掉
          this.saleItemList.splice(row.index - 1, 1)
          this.$message.success(this.$t('sale_cash_cash_262'))
        } else if (response.data == -2) {
          this.$message.error(this.$t('sale_cash_cash_263'))
        } else if (response.data == -1) {
          this.$message.error(this.$t('sale_cash_cash_264'))
        }
      })
    },
    // 修改商品数量
    handleChangeQuantity(row) {
      this.standardizeUpdateSaleParams(row)
      this.updateSaleItem.originalSpeId = Number(row.speId)
      this.updateSaleItem.finalSpeId = Number(row.speId)
      changeSaleItem(this.updateSaleItem).then((response) => {
        if (response.data == 1) {
          this.$message.success(this.$t('sale_cash_cash_265'))
        } else if (response.data == -2) {
          this.$message.error(this.$t('sale_cash_cash_263'))
        } else if (response.data == -1) {
          this.$message.error(this.$t('sale_cash_cash_264'))
        }
        this.updateSaleItem = {}
      })
    },
    // 录入商品
    enterItem() {
      this.$refs.enterItemForm.validate(valid => {
        if (valid) {
          this.enterItemForm.speId = Number(this.enterItemForm.speId)
          enterItem(this.enterItemForm).then((response) => {
              // 已录入，库存足
              if (response.data && Object.values(response.data).every(value => value === null)) {
                this.$message.success(this.$t('sale_cash_cash_266'))
                const y = this.saleItemList.findIndex(item => {
                  return item.productSn === this.enterItemForm.productSn && item.speId.toString() === this.enterItemForm.speId.toString()
                })
                this.$set(this.saleItemList[y], 'quantity', this.saleItemList[y].quantity + this.enterItemForm.quantity)
              }
              // 未录入，库存足
              else if (response.data.quantity != -1) {
                this.$message.success(this.$t('sale_cash_cash_266'))
                this.saleItemList.push(response.data)
              }
              this.$refs['enterItemForm'].resetFields()
            }
          ).catch(error => {
            if (error.response) {
              if (error.response.message) {
                let errorMessage = error.response.message || this.$t('sale_cash_cash_267')
                this.$message.error(errorMessage)
              }
            } else if (error.request) {
              this.$message.error(this.$t('sale_cash_cash_268'))  // 请求已发出，但没有收到任何响应
            }
            this.$refs['enterItemForm'].resetFields()
          })
        } else {
          this.$message.error(this.$t('sale_cash_cash_269'))
        }
      })
    },
    // 步骤3：结束输入
    endSale() {
      endSale(this.orderInfo.note).then((response) => { // 传入备注
        // console.log(response.data)
        this.orderInfo.total = response.data.total
        this.orderInfo.quantity = response.data.quantity
        this.step = 4
      })
    },
    // 打开支付界面
    openMakePayment() {
      this.openPayment(this.orderInfo.saleNo)
    },
    // 步骤4：提交支付
    makePayment() {
      this.$refs.makePaymentForm.validate(valid => {
        if (valid) {
          // 判断下拉框选择的是1还是2
          if (this.makePaymentForm.payType == 1) {
            // 1. 现金支付
            // A2. 封装需要传送的data
            const payData = {
              saleNo: this.orderInfo.saleNo,
              amount: this.makePaymentForm.cashTendered
            }
            // A2. 调用现金支付接口
            cashPay(payData).then((response) => {
              if (response.data >= 0) {
                this.$message.success(this.$t('sale_cash_cash_270'))
                this.changeDue = response.data
                this.orderInfo.status = this.$t('sale_cash_cash_271')
                this.step = 1
                this.querypaymentDetail()
                setTimeout(() => {
                  this.clear()
                }, 1000)
              } else {
                this.$message.error(response.data)
              }
            })
          } else if (this.makePaymentForm.payType == 2) {
            // 2. 支付宝支付
            this.performAlipayPayment()
            // 弹出对话框，询问是否支付
            this.alipayOpen = true
          }
        } else {
          this.$message.error(this.$t('sale_cash_cash_272'))
          this.makePaymentForm.cashTendered = ''
        }
      })
    },
    // 查询支付宝支付状态
    queryAliPayment() {
      verifyAliPay(this.orderInfo.saleNo).then((response) => {

        const result = response.data
        // console.log(result)
        if (result == true) {
          this.$message.success(this.$t('sale_cash_cash_270'))
          this.orderInfo.status = this.$t('sale_cash_cash_271')
          this.step = 1
          this.alipayOpen = false
          this.querypaymentDetail()
          setTimeout(() => {
            this.clear()
          }, 1000)
        } else {
          this.$message.error(this.$t('sale_cash_cash_273'))
        }
      })
    },
    // 处理支付宝支付逻辑
    performAlipayPayment() {
      const payData = {
        saleNo: this.orderInfo.saleNo,
        amount: this.makePaymentForm.cashTendered
      }

      // 调用支付宝支付接口获取支付表单的HTML
      aliPay(payData).then(response => {
        if (typeof response.data === 'string' && response.data.startsWith('<form')) {
          // 假设response.data是一个完整的HTML表单字符串
          // console.log(response.data)
          this.loadAlipayForm(response.data)
        } else {
          this.$message.error(this.$t('sale_cash_cash_274'))
        }
      })
        .catch(error => {
          console.error(this.$t('sale_cash_cash_275'), error)
          this.$message.error(this.$t('sale_cash_cash_276'))
        })
    },

    // 加载支付宝支付表单到iframe
    loadAlipayForm(formHtml) {
      // 只保留 form 部分，自定义启动
      var endIdx = formHtml.indexOf('<script>')
      formHtml = formHtml.substring(0, endIdx)
      // 将 jsonp 插入网页
      var container = document.createElement('div')
      container.innerHTML = formHtml
      document.body.appendChild(container)
      // console.log(container)
      // 执行表单，打开支付页面
      var formElement = container.querySelector('form')
      formElement.target = '_blank'
      formElement.submit()
    },

    // 查询订单支付明细
    querypaymentDetail() {
      getPayDetail(this.orderInfo.saleNo).then((response) => {
        this.paymentDetailForm = response.data
        this.paymentOpen = false
        this.paymentDetailOpen = true
        // console.log(this.paymentDetailForm)
        // console.log(response.data)
      })
    },
    // 删除一行订单明细
    handleDelete(row) {
      deleteItem(row.productSn, Number(row.speId)).then((response) => {
        if (response.data == 1) {
          this.$message.success(this.$t('sale_cash_cash_277'))
          this.saleItemList.splice(row.index - 1, 1)
        } else if (response.data == 2) {
          this.$message.error(this.$t('sale_cash_cash_278'))
        }
      })
    },
    // 清空界面数据
    clear() {
      this.orderInfo = {}
      this.changeDue = ''
      this.saleItemList = []
      // this.$refs['makePaymentForm'].resetFields()
      this.step = 1
    },
    //为table订单明细添加序号
    rowSaleItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    // 重置商品录入form
    clearEnterItemForm() {
      this.$refs['enterItemForm'].resetFields()
    },
    //继续为完成订单
    continueSale(row) {
      // console.log(this)
      // todo
      this.clear()
      this.unfinishedOpen = false
      loadSale(row.saleNo).then((response) => {
        this.clear()
        this.saleItemList = response.data.itemDisplayVOs
        // 如果订单状态为挂单中，则继续完成订单
        if (response.data.status == 1) {
          this.step = 2
          this.orderInfo.saleNo = response.data.saleNo
          this.orderInfo.note = response.data.note
          this.orderInfo.status = this.$t('sale_cash_cash_229')
        }
        // 如果订单状态为已预定未付款，则只显示支付框框
        else if (response.data.status == 2) {
          this.step = 4
          this.orderInfo.saleNo = response.data.saleNo
          this.openPayment(this.orderInfo.saleNo)
          this.orderInfo.note = response.data.note
          this.orderInfo.total = response.data.total
          this.orderInfo.quantity = response.data.saleQuantity
          this.orderInfo.status = this.$t('sale_cash_cash_230')
        }
        this.enterItemForm = {}
        this.enterItemForm.quantity = 1
      })
    },
    // 开启支付（查询订单的价格数据）
    openPayment(saleNo) {
      // 更新makePaymentForm
      openPay(saleNo).then((response) => {
        // console.log(response.data)
        this.makePaymentForm.total = response.data.total
        this.makePaymentForm.preferentialTotal = response.data.preferentialTotal
        this.makePaymentForm.discount = response.data.differ
        this.makePaymentForm.cashTendered = response.data.preferentialTotal
        this.paymentOpen = true
      })
    },
    //查询、查看未完成订单
    queryUnfinishedSale(button) {
      // 查询所有未完成订单
      if (button === 'queryAll') {
        this.unfinishedOpen = true
        this.resetQueryUnfinishedSale()
      }
      getUnfinishedSale(this.queryUnfinishedSaleParams).then((response) => {
        this.unfinishedData = response.data
      })
    },
    //重置未完成订单查询框
    resetQueryUnfinishedSale() {
      this.queryUnfinishedSaleParams = {}
    },
    //挂单
    pendingOrders() {
      pendingSale(this.orderInfo.note).then((response) => { //  传入备注
        if (response.data == this.$t('sale_cash_cash_279')) {
          this.$message.success(response.data)
          this.clear()
          this.step = 1
        } else {
          this.$message.error(response.data)
        }
      })
    },
    // 取消订单
    cancelOrder() {
      cancelOrder(this.orderInfo.saleNo).then((response) => {
        if (response.data == 1) {
          this.clear()
          this.step = 1
          this.$message.success(this.$t('sale_cash_cash_280'))
        } else {
          this.$message.error(this.$t('sale_cash_cash_281'))
        }
      })
    },
    // 打开备注弹出框
    openBeizhu() {
      this.$prompt(this.$t('sale_cash_cash_282'), this.$t('sale_cash_cash_198'), {
        confirmButtonText: this.$t('sale_cash_cash_283'),
        cancelButtonText: this.$t('sale_cash_cash_284')
      }).then(({ value }) => {
        this.$set(this.orderInfo, 'note', value)
      })
    }
  }
}
</script>

<style>
.unfinish-Button,
.unfinish-Button:hover {
  font-size: 13px;
  height: 35px;
  color: white;
  margin-top: 20px;
  background-color: #88a9ea;
}

.unfinish-Button:hover {
  background-color: #a8c3f9;
}

.enterItemButton,
.enterItemButton:hover {
  background-color: #f5bac1;
}

.enterItemButton:hover {
  background-color: #f9d3d7;
  color: white;
}

.resetButton,
.resetButton:hover {
  background-color: #edf8f6;
}

.resetButton:hover {
  background-color: #b3cec9;
  color: white;
}

.endSaleButton,
.endSaleButton:hover {
  background-color: #409eff;
}

.endSaleButton:hover {
  background-color: #96c7f8;
  color: white;
}

.unfinishedDialogResetButton,
.unfinishedDialogResetButton:hover {
  background-color: #b9e5dd;
  color: white;
}

.unfinishedDialogResetButton:hover {
  background-color: #73b5a9;
}

.unfinishedDialogQueryButton,
.unfinishedDialogQueryButton:hover {
  background-color: #abc2a9;
  color: white;
}

.unfinishedDialogQueryButton:hover {
  background-color: #d0ebce;
}

.paymentButton {
  display: block;
  width: 100%;
}

.marquee-container {
  margin-left: 170px;
  /* border:2px solid black; */
  top: -13px;
  width: 350px;
  overflow: hidden;
  white-space: nowrap;
  position: relative; /* 确保动画定位正确 */
}

.marquee-text {
  display: inline-block;
  color: #dc9505;
  font-size: 16px;
  will-change: transform; /* 优化动画性能 */
}

@keyframes marquee {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}
</style>
